package com.zw.admin.server.service.impl;

import com.zw.admin.server.dao.StrategyDao;
import com.zw.admin.server.dto.strategy.*;
import com.zw.admin.server.model.Device;
import com.zw.admin.server.model.ResponseBean;
import com.zw.admin.server.model.Strategy;
import com.zw.admin.server.model.StrategyDevice;
import com.zw.admin.server.service.DeviceService;
import com.zw.admin.server.service.StrategyService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("strategyService")
public class StrategyServiceImpl implements StrategyService {
    @Autowired
    private StrategyDao strategyDao;

    @Autowired
    private DeviceService deviceService;

    @Override
    public void taskTest() {
        log.info("----测试quatz定时任务是否可以执行----");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertStrategy(AddStrategyDto strategyDto) {
        strategyDao.insertStrategy(strategyDto);
        //获取策略主表id
        Integer strategyId = strategyDto.getStrategyId();

        List<StrategyDevice> list = new ArrayList<>();
        strategyDto.getDeviceId().forEach(temp ->{
            list.add(StrategyDevice.builder().strategyId(strategyId).deviceId(temp).build());
        });
        strategyDao.insertStrategyDevice(list);
    }

    @Override
    public List<Device> getDeviceList(@Param("spaceId") Integer spaceId) {
        return strategyDao.getDeviceList(spaceId);
    }

    @Override
    public List<AddStrategyVo> queryStrategy() {
        return strategyDao.queryStrategyPage();
    }

    @Override
    public void deleteStrategy(Integer strategyId) {
        strategyDao.deleteStrategyDevice(strategyId);
        strategyDao.deleteStrategy(strategyId);
    }

    @Override
    public void updateStrategy(AddStrategyDto strategyDto) {
        List<String> newDv = strategyDto.getDeviceId();
        strategyDao.updateStrategy(strategyDto);
        Integer strategyId = strategyDto.getStrategyId();
        List<String> oldDv = strategyDao.getStrategyDeviceId(strategyId);
        updateStrategyDevice(oldDv,newDv,strategyId);
    }

    @Override
    public List<DealStrategyResultDto> dealStrategyDevice(DealStrategyDto dealStrategyDto) {
        Integer operation = dealStrategyDto.getOperation();
        List<Integer> list = dealStrategyDto.getStrategyId();
        if(list==null || list.size() == 0){
            throw new RRException("策略id不能为空",100);
        }
        List<DealStrategyResultDto> dtoList = new ArrayList<>();
        for(Integer strategyId : list){
            List<String> deviceIds = strategyDao.getStrategyDeviceId(strategyId);
            List<FailReasonVo> failReasonVoList = new ArrayList<>();
            if(deviceIds != null && deviceIds.size() > 0){
                deviceIds.forEach(temp -> {
                    FailReasonVo failReasonVo = dealDevice(temp,operation);
                    failReasonVoList.add(failReasonVo);
                });
            }
            dtoList.add(DealStrategyResultDto.builder().strategyId(strategyId).deviceResult(failReasonVoList).build());
        }
        return dtoList;
    }

    public void updateStrategyDevice(List<String> oldDv, List<String> newDv,Integer strategyId){
        List<String> tempDv = new ArrayList<>();
        tempDv.addAll(oldDv);
        tempDv.removeAll(newDv);
        //从表里删除已经不存在的
        if(tempDv.size() > 0){
            strategyDao.deleteStrategyDeviceList(tempDv);
        }
        List<String> tempNewDv = new ArrayList<>();
        tempNewDv.addAll(newDv);
        tempDv.removeAll(oldDv);
        //新增新加入的设备
        if(tempNewDv.size() > 0){
            List<StrategyDevice> list = new ArrayList<>();
            tempNewDv.forEach(temp ->{
                list.add(StrategyDevice.builder().strategyId(strategyId).deviceId(temp).build());
            });
            strategyDao.insertStrategyDevice(list);
        }
    }

    /**
     * 调用设备接口接收返回值
     * @param deviceId
     * @param operation
     */
    public FailReasonVo dealDevice(String deviceId, Integer operation){
        ResponseBean responseBean = deviceService.updateDeviceStates(deviceId,operation+"");
        if(200 == responseBean.getCode()){
            strategyDao.updateDeviceState(StrategyDevice.builder().deviceId(deviceId)
                    .state(DeviceState.SUCCESS.getCode()).result("").build());
            return FailReasonVo.builder().code(200).failReason("").build();
        }else{
            strategyDao.updateDeviceState(StrategyDevice.builder().deviceId(deviceId)
                    .state(DeviceState.FAILED.getCode()).result(responseBean.getMsg()).build());
            return FailReasonVo.builder().code(500).failReason(responseBean.getMsg()).build();
        }
    }

}
